<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> 
<html>
<head>
<title>Functions in PHP</title>
<link rel="stylesheet" href="/cfg/format.css" type="text/css">
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<meta name="keywords" content="PHP, learn PHP, functions, tutorial, programming language">
<meta name="description" content="In this part of the PHP tutorial, we cover functions.">
<meta name="language" content="en">
<meta name="author" content="Jan Bodnar">
<meta name="distribution" content="global">

<script type="text/javascript" src="/lib/jquery.js"></script>
<script type="text/javascript" src="/lib/common.js"></script>

</head>

<body>

<div class="container">

<div id="wide_ad" class="ltow">
<script type="text/javascript"><!--
google_ad_client = "pub-9706709751191532";
/* 160x600, August 2011 */
google_ad_slot = "2484182563";
google_ad_width = 160;
google_ad_height = 600;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script>
</div>

<div class="content">

<a href="/" title="Home">Home</a>&nbsp;
<a href="..">Contents</a>


<h1>Functions in PHP</h1>

<p>
In this part of the PHP programming tutorial, we will talk about functions. 
</p>

<p>
A function is a piece of code in a larger program. The function performs a 
specific task. The advantages of using functions are:
</p>

<ul>
    <li>Reducing duplication of code</li>
    <li>Decomposing complex problems into simpler pieces</li>
    <li>Improving clarity of the code</li>
    <li>Reuse of code</li>
    <li>Information hiding</li>
</ul>

<div class="center">
<script type="text/javascript"><!--
google_ad_client = "ca-pub-9706709751191532";
/* top_horizontal */
google_ad_slot = "3327173442";
google_ad_width = 468;
google_ad_height = 60;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script>
</div>

<p>
There are two basic types of functions. Built-in functions and user defined ones. 
The built-in functions are part of the
PHP language. Examples are: <code>phpinfo()</code>, 
<code>round()</code> or <code>abs()</code>.
The user defined functions are created by application programmers to cover their needs. 
They are created with the <code>function</code> keyword. 
</p>


<h2>Defining functions</h2>

<p>
A function is created with the <code>function</code> keyword. 
</p>

<pre class="code">
&lt;?php

function displayVersion() {
    echo "this is PHP " . phpversion();
    echo "\n";
}
displayVersion();

?&gt;
</pre>

<p>
The function keyword is followed by the function name with round brackets.
The body of the function lies between 
the curly brackets. 
We say that we <b>call</b> a function.
If we call a function, the statements inside the function body are executed.   
</p>

<pre class="explanation">
 displayVersion();
</pre>

<p>
This line of the code calls the function.
</p>

<pre>
$ php simple.php 
this is PHP 5.2.6-2ubuntu4.5
</pre>

<p>
Here we see the outcome of the script. 
</p>

<h2>The return keyword</h2>

<p>
The <b>return</b> keyword is used to return a value from the function.
A function may or may not return a value. 
</p>

<pre class="code">
&lt;?php

function maximum($x, $y) {
    if ($x > $y) return $x;
    else return $y;
}

$a = 23;
$b = 32;

$val = maximum($a, $b);
echo "The max of $a, $b is $val \n";

?&gt;
</pre>

<p>
We have a maximum() function. It returns a max for two numbers. We could not name it max, because
there is already a built-in max() function. 
</p>

<pre class="explanation">
 if ($x > $y) return $x;
 else return $y;
</pre>

<p>
If the $x variable is greater than $y, we return $x. Otherwise we return $y.
</p>

<pre class="explanation">
 $val = maximum($a, $b);
</pre>

<p>
The value returned by the maximum() function is assigned to the $val 
variable.
</p>

<pre class="explanation">
 echo "The max of $a, $b is $val \n";
</pre>

<p>
We print the max value of the two numbers to the console.
</p>


<h2>Function arguments</h2>

<p>
Most functions accept arguments. Arguments are values, that are sent to the function. 
The functions process the values and possibly return them back.
</p>

<pre class="code">
&lt;?php

function FTC($c) {
    return $c * 9/5 + 32;
}

echo FTC(100);
echo "\n";
echo FTC(0);
echo "\n";
echo FTC(30);
echo "\n";

?&gt;
</pre>

<p>
In our example, we convert Fahrenheit temperature to Celsius. 
The FTC function accepts one argument $c, which is the
Celsious temperature.
</p>

<pre>
$ php fahrenheit.php 
212
32
86
</pre>

<h2>Implicit values</h2>

<p>
The arguments in PHP functions may have implicit values. An implicit value is used, if no value is provided. 
</p>

<pre class="code">
&lt;?php

function power($a, $b=2) {

    if ($b == 2) {
        return $a*$a;
    }

    $value = 1;

    for ($i = 0; $i &lt; $b; $i++) {
        $value *= $a;
    }
    return $value;
}

$v1 = power(5);
$v2 = power(5, 4);

echo "5^2 is $v1 \n";
echo "5^4 is $v2 \n";

?&gt;
</pre>

<p>
Here we created a power function. The function has one argument with an implicit value. 
We can call the function with one or two arguments. 
</p>

<pre>
$ php implicit.php 
5^2 is 25 
5^4 is 625 
</pre>


<h2>Static variables</h2>

<p>
A <b>static</b> variable is a variable that has been allocated statically, 
whose lifetime extends across the entire run of the program. (Wikipedia)
The default, local variables do not retain their value within consecutive calls of the function. 
</p>


<pre class="code">
&lt;?php

function nonstatic() {
    $value = 0;
    $value += 1;

    return $value;
}

nonstatic();
nonstatic();
nonstatic();
nonstatic();
echo nonstatic(), "\n";

?&gt;
</pre>

<p>
In the above example, we have a normal, nonstatic variable. We increment the variable each time the 
function is called. We call the function 5 times. However, nonstatic variables are initiated for each
call of the function. After 5 function calls the $value equals to 1. 
</p>

<p>
The static variables are initiated only once, when the function is first called. They retain their
value afterwards. 
</p>

<pre class="code">
&lt;?php

function staticfun() {
    static $value = 0;
    $value += 1;

    return $value;
}

staticfun();
staticfun();
staticfun();
staticfun();
echo staticfun(), "\n";

?&gt;
</pre>

<p>
After 5 consecutive calls, the $value is equal to 5. 
</p>

<pre>
$ php nonstatic.php 
2
$ php static.php 
6
</pre>


<h2>Passing arguments by value, by reference</h2>

<p>
PHP supports two ways of passing arguments to functions. The default
way is passing arguments by value. When we pass arguments by value, the function
works only with the copies of the values. This may lead to performance overheads, when we
work with large amounts of data. 
</p>

<p>
When we pass values by reference, the function receives a reference to the actual values. 
The original values are affected, when modified. This way of passing 
values is more time and space efficient.
On the other hand, it is more error prone. 
</p>

<p>
Which way of passing arguments should we use? It depends on the situation. 
Say we have a set of data, salaries of 
employees. If we want to compute some statistics of the data, we do 
not need to modify them. We pass by values.
If we work with large amounts of data and the speed of computation 
is critical, we pass by reference. If we want to modify
the data, e.g. do some reductions or raises to the salaries, 
we might pass by reference. 
</p>

<p>
The following two examples cover both concepts. 
</p>

<pre class="code">
&lt;?php

function swap($a, $b) {
    $temp = $a;
    $a = $b;
    $b = $temp;
    echo "inside swap function:\n";
    echo "\$a is $a \n";
    echo "\$b is $b \n";
}

$a = 4;
$b = 7;

echo "outside swap function:\n";
echo "\$a is $a \n";
echo "\$b is $b \n";

swap($a, $b);

echo "outside swap function:\n";
echo "\$a is $a \n";
echo "\$b is $b \n";

?&gt;
</pre>

<p>
The swap function swaps the numbers between the $a, $b variables. The original variables
are not affected. 
</p>

<pre class="explanation">
 $a = 4;
 $b = 7;
</pre>

<p>
At the beginning, these two variables are initiated. 
</p>

<pre class="explanation">
 swap($a, $b);
</pre>

<p>
We call the swap function. The function takes $a, $b variables as
parameters.  
</p>

<pre class="explanation">
 $temp = $a;
 $a = $b;
 $b = $temp;
</pre>

<p>
Inside the swap function, we change the values. Note that the $a, $b variables are
defined locally. They are valid only inside the swap function. 
</p>


<pre>
$ php swap.php 
outside swap function:
$a is 4 
$b is 7 
inside swap function:
$a is 7 
$b is 4 
outside swap function:
$a is 4 
$b is 7 
</pre>

<p>
The output shows, that the original variables were not affected. 
</p>


<p>
The next code example passes values to the function by reference. 
The original variables are changed inside the swap function. 
</p>

<pre class="code">
&lt;?php

function swap(&$a, &$b) {
    $temp = $a;
    $a = $b;
    $b = $temp;
    echo "Inside the swap function:\n";
    echo "\$a is $a \n";
    echo "\$b is $b \n";
}

$a = 4;
$b = 7;

echo "Outside the swap function:\n";
echo "\$a is $a \n";
echo "\$b is $b \n";

swap($a, $b);

echo "Outside the swap function:\n";
echo "\$a is $a \n";
echo "\$b is $b \n";

?&gt;
</pre>

<p>
We use the &amp; character to pass values by reference. 
</p>

<pre class="explanation">
 function swap(&amp;$a, &amp;$b) {
 ...  
 }
</pre>

<p>
The example is almost identical to the previous one. Except for the
ampersand characters. 
</p>

<pre>
$ php swap2.php 
Outside the swap function:
$a is 4 
$b is 7 
Inside the swap function:
$a is 7 
$b is 4 
Outside the swap function:
$a is 7 
$b is 4 
</pre>

<p>
Here we see, that the swap function really changed the values of the variables. 
</p>


<h2>Recursion</h2>

<p>
Recursion, in mathematics and computer science, is a method of defining functions 
in which the function being defined is applied within its own definition. (Wikipedia)
In other words, a recursive function calls itself to do its job.
Recursion is a widely used approach to solve many programming tasks. 
</p>

<p>
A typical example is calculation of the factorial.
</p>

<pre class="code">
&lt;?php

function factorial($n) {

    if ($n==0) {
        return 1;
    } else {
        return $n * factorial($n - 1);
    }
}


echo factorial(4), "\n";
echo factorial(10), "\n";

?&gt;
</pre>

<p>
In this code example, we calculate the factorial of two
numbers. 
</p>

<pre class="explanation">
 return $n * factorial($n - 1);
</pre>

<p>
Inside the body of the factorial function, we call the factorial function
with a modified argument. The function calls itself.
</p>

<pre>
$ php recursion.php 
24
3628800
</pre>

<p>
These are the results.
</p>

<h2>Global and local variables</h2>

<p>
Next we will talk about the scope of the variables
in PHP. A <b>scope</b> is the range in which a variable can be referenced.
When we work with functions, there are two basic scopes. The global and the local scope. 
The local scope is also called a function scope. 
</p>

<pre class="code">
&lt;?php

$value = 1;

function simple() {
    var_dump($value);
}

simple();

?&gt;
</pre>

<p>
A variable defined outside a function body cannot be referenced within
a function.
</p>

<pre>
$ php scope.php 
NULL
</pre>

<p>
The $value variable is NULL in the simple() function.
</p>


<pre class="code">
&lt;?php

$value = 4;

function simple() {
    $value = 3;
    echo $value, "\n";
}

simple();

echo $value, "\n";

?&gt;
</pre>

<p>
In this example, we have two variables with the same name. 
They do not collide, because they exist in different scopes. 
</p>

<pre>
$ php scope1.php 
3
4
</pre>

<p>
The value is 3 inside the function. 4 outside the function.
</p>

<p>
In the next example, we will modify a value inside the
function.
</p>

<pre class="code">
&lt;?php

$value = 1;

function simple() {
    global $value;
    $value = 2;
}

echo $value, "\n";
simple();
echo $value, "\n";

?&gt;
</pre>

<p>
We use the <code>global</code> keyword to reference
a variable defined outside the body of the function. 
</p>

<pre>
$ php scope2.php 
1
2
</pre>

<p>
The $value was successfully modified inside the simple() function.
</p>

<p>
In this part of the PHP tutorial, we covered PHP functions. 
</p>


<div class="center"> 
<script type="text/javascript"><!--
google_ad_client = "pub-9706709751191532";
/* horizontal */
google_ad_slot = "1734478269";
google_ad_width = 468;
google_ad_height = 60;
//-->
</script> 
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js"> 
</script> 
</div> 
<br> 


<div class="botNav, center">
<span class="botNavItem"><a href="/">Home</a></span> ‡ <span class="botNavItem"><a href="..">Contents</a></span> ‡  
<span class="botNavItem"><a href="#">Top of Page</a></span>
</div>

<div class="footer">
<div class="signature">
<a href="/">ZetCode</a> last modified January 17, 2010  <span class="copyright">&copy; 2007 - 2013 Jan Bodnar</span>
</div>
</div>

</div> <!-- content -->

</div> <!-- container -->

</body>
</html>

